#! /usr/bin/env python
# -*- coding: utf8 -*-

import cElementTree as et
import sys

if len(sys.argv) != 3:
    print 'Reads a file containing list of "positions" in an XML file, and generates a separated file for each list.'
    print "The lists on the file must be on the same format as python lists: [ele1, ele2, ..., elen]"
    print 'Usage: %s <xml file> <list file>' % (sys.argv[0])
    sys.exit(0)

# the root of all the evil
root  = et.parse(sys.argv[1]).getroot()
nodes = root.getchildren()
print "Parsing complete"

# fetches the list of nodes to mess
fp    = open(sys.argv[2], "r")
lists = fp.readlines()
fp.close()

basename = sys.argv[1].split(".")[0]

for c, i in enumerate(lists):
    exec("l = %s" % (i,))
    
    new_root = et.Element(root.tag)
    new_tree = et.ElementTree(new_root)
    
    for j in l:
        new_root.append(nodes[int(j)])

    new_tree.write("%s-%.2d.xml" % (basename, c))
    print "%s-%.2d.xml written" % (basename, c)
